package com.rock.code.bigdata.bigdatainterface.service.impl;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rock.code.bigdata.bigdatainterface.dao.HistoryDataDao;
import com.rock.code.bigdata.bigdatainterface.domain.Constants;
import com.rock.code.bigdata.bigdatainterface.domain.ManageObject;
import com.rock.code.bigdata.bigdatainterface.domain.TbCdeInformation;
import com.rock.code.bigdata.bigdatainterface.service.HistoryDataService;
import com.rock.code.bigdata.bigdatainterface.util.MyUtil;
import com.rock.code.common.comm.RandomGUID;
import com.rock.code.hdfs.HdfsAPP;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.rock.code.bigdata.bigdatainterface.util.MyUtil.*;

@Service
public class HistoryDataServiceImpl implements HistoryDataService {
    private Logger logger = Logger.getLogger(HistoryDataServiceImpl.class);
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");

    @Resource
    private HistoryDataDao historyDataDao;

    @Override
    public void deleteAll() {
        historyDataDao.deleteAllData();
    }


    @Override
    public List<HashMap> querySqlResultBySql(Map<String, Object> param) {
        return historyDataDao.querySqlResultBySql(param);
    }

    @Override
    public void getHisDataByThread(String ip, String startTime, String endTime, String timeFlag) throws IOException {
        String fileClass = null;
        //地区标志
        String areaFlag = null;
        if (Constants.IP_BEIJING.equals(ip)) {
            fileClass = "originBeijing";
            areaFlag = "100";
        } else if (Constants.IP_SHANGHAI.equals(ip)) {
            fileClass = "originShanghai";
            areaFlag = "101";
        } else if (Constants.IP_NANJING.equals(ip)) {
            fileClass = "originNanjing";
            areaFlag = "102";
        } else if (Constants.IP_TIANJIN.equals(ip)) {
            fileClass = "originTianjin";
            areaFlag = "103";

        }
        // 新启动一个线程
        // 插入一条日志记录接口调用情况（tb_coll_data_logs）
        try {
            Thread.sleep(15000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        List<ManageObject> managementList = historyDataDao.getManageDataByAreaflag(areaFlag);
        String date = stampToDate1(startTime);
        String timeDay = date.split(" ")[0].replaceAll("-", "");
        String[] arrSt = date.split(" ")[0].split("-");
        String year = null;
        String month = null;
        for (int i = 0; i < arrSt.length; i++) {
            year = arrSt[0];
            month = arrSt[1];
        }
        String filename = null;
        if ("0".equals(timeFlag)) {
            filename = "hisData" + timeDay + ".txt";

        } else if ("1".equals(timeFlag)) {
            filename = "hisData" + year + month + "%" + System.currentTimeMillis() + ".txt";

        }
        String file = "/root/datas/" + filename;
        String url = "http://" + ip + ":9200/api/v1/datapoints/query";
        String hosttype = null;
        String domain = null;
        String uuid = null;
        String kpiCode = null;
        String classname = null;
        String ext_unitid = null;
        String unidId = null;
        List<Map> classList;


        //添加计数器记录遍历管理对象数量
        int sum = 0;
        for (ManageObject manageobject : managementList) {
            sum++;
            hosttype = manageobject.getClassName();
            domain = manageobject.getDomain();
            uuid = manageobject.getUuid();
            ext_unitid = hosttype + ":" + domain + ":" + uuid;  //classname:domain:uuid
            //得到管理对象指标列表
            classList = historyDataDao.getkpiListByClassname(hosttype, "1");
            //遍历管理对象
            for (Map map : classList) {
                classname = (String) map.get("KPI_NAME");
                kpiCode = (String) map.get("KPI_CODE");
                //封装请求参数
                JSONObject params = new JSONObject();
                JSONArray jsonArray = new JSONArray();
                JSONObject jsonMo = new JSONObject();
                String[] arr = {hosttype + ".domain=\"" + domain + "\",uuid=\"" + uuid + "\""};
                jsonMo.put("mo", arr);
                JSONObject jsonTags = new JSONObject();
                jsonTags.put("tags", jsonMo);
                jsonTags.put("name", classname);
                jsonArray.add(jsonTags);
                params.put("metrics", jsonArray);
                params.put("start_absolute", startTime);
                params.put("end_absolute", endTime);
                //调用请求接口
                JSONObject jsonObject = null;
                boolean flag = false;
                int times = 0;
                do {
                    try {
                        jsonObject = MyUtil.doPost(url, params);
                    } catch (Exception e) {
                        e.printStackTrace();
                        logger.warn("WARN!" + "取对象= " + ext_unitid + ",指标=" + classname + ",kpicode=" + kpiCode + ",异常，进行重试！");
                        logger.info("请求参数为：==========" + params);
                        try {
                            Thread.sleep(5000);
                        } catch (Exception e1) {
                            e1.printStackTrace();
                        }
                        flag = true;
                        jsonObject = null;
                        logger.info("请求次数==========" + times);

                        times++;
                        if (times > 5) {
                            break;
                        }
                    }
                } while (flag);
                if (jsonObject == null) {
                    continue;
                }
                unidId = ext_unitid + ":" + classname;
                //解析返回的历史数据
                String queries = jsonObject.getString("queries");
                if ("".equals(queries) || queries == null) {
                    continue;
                }
                JSONArray queriesArray = JSONArray.parseArray(queries);
                String resultsJson = queriesArray.getJSONObject(0).getString("results");
                if ("".equals(resultsJson) || resultsJson == null) {
                    continue;
                }
                JSONArray resultArray = JSONArray.parseArray(resultsJson);
                String valueJson = resultArray.getJSONObject(0).getString("values");
                if ("".equals(valueJson) || valueJson == null) {
                    continue;
                }
                JSONArray array = JSONArray.parseArray(valueJson);
                //将数据输出到文本文档中
                for (int i = 0; i < array.size(); i++) {
                    String time = String.valueOf(array.getJSONArray(i).get(0));
                    String colldata = kpiCode + "\001" + unidId + "\001" + stampToDate(time) + "\001" + stampToDate(time) + "\001" + array.getJSONArray(i).get(1) + "\001" + ext_unitid + "\001" + areaFlag;
                    appendData(file, colldata);

                }

            }
            logger.info(areaFlag + "管理对象采集完成数量：" + sum);
        }

        //查询管理对象列表
        List<ManageObject> managementListChild = historyDataDao.getManageDataByAreaflag(areaFlag);
        String childValue = null;
        String childName = null;
        String childId = null;

        //加入子对象数据的采集
        //1.获取子对象列表
        int sumChild = 0;
        for (ManageObject manageObject : managementListChild) {
            sumChild++;
            uuid = manageObject.getUuid();
            hosttype = manageObject.getClassName();
            domain = manageObject.getDomain();
            ext_unitid = hosttype + ":" + domain + ":" + uuid;
            //根据管理对象类型查看子对象和uuid
            List<String> childList = historyDataDao.queryChildInfByClassname(manageObject.getClassName());
            if (childList.size() == 0) {
                continue;
            }
            for (int i = 0; i < childList.size(); i++) {
                childName = childList.get(i);
                String urlChild = "http://" + ip + ":8082/query/mo/" + childName + "?where=uuid='" + uuid + "'";
                JSONArray result = null;
                try {
                    result = doGetArray(urlChild);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                //解析结果
                for (int j = 0; j < result.size(); j++) {

                    JSONObject job = result.getJSONObject(j);
                    String pro = job.getString("properties");
                    JSONArray proArray = JSONArray.parseArray(pro);
                    for (int k = 0; k < proArray.size(); k++) {
                        JSONObject jsonObject = proArray.getJSONObject(k);
                        if ("name".equals(jsonObject.getString("name")))
                            //子对象值
                            childValue = JSONObject.parseObject(jsonObject.getString("value")).getString("value");
                        if ("id".equals(jsonObject.getString("name")))
                            //子对象id
                            childId = JSONObject.parseObject(jsonObject.getString("value")).getString("value");
                    }

                    List<Map> kpiList = historyDataDao.getChildListByClassname(childName, "1");
                    //遍历子对象名称列表
                    for (Map map : kpiList) {
                        classname = (String) map.get("KPI_NAME");
                        kpiCode = (String) map.get("KPI_CODE");
                        //封装请求参数
                        JSONObject params = new JSONObject();
                        JSONArray jsonArray = new JSONArray();
                        JSONObject jsonMo = new JSONObject();
                        String[] arr = {childName + ".id=\"" + childId + "\",name=\"" + childValue + "\",uuid=\"" + uuid + "\""};
                        jsonMo.put("mo", arr);
                        JSONObject jsonTags = new JSONObject();
                        jsonTags.put("tags", jsonMo);
                        jsonTags.put("name", classname);
                        jsonArray.add(jsonTags);
                        params.put("metrics", jsonArray);
                        params.put("start_absolute", startTime);
                        params.put("end_absolute", endTime);

                        //调用请求接口
                        JSONObject jsonObject = null;
                        boolean flag = false;
                        int times = 0;
                        do {
                            try {
                                jsonObject = MyUtil.doPost(url, params);
                            } catch (Exception e) {
                                e.printStackTrace();
                                logger.warn("WARN!" + "取对象= " + ext_unitid + ",指标=" + classname + ",kpicode=" + kpiCode + ",异常，进行重试！");
                                logger.info("请求参数为：==========" + params);
                                try {
                                    Thread.sleep(5000);
                                } catch (Exception e1) {
                                    e1.printStackTrace();
                                }
                                flag = true;
                                jsonObject = null;
                                logger.info("请求次数==========" + times);

                                times++;
                                if (times > 5) {
                                    break;
                                }
                            }
                        } while (flag);
                        if (jsonObject == null) {
                            continue;
                        }
                        unidId = ext_unitid + ":" + childValue + ":" + classname;
                        //解析返回的历史数据
                        String queries = jsonObject.getString("queries");
                        if ("".equals(queries) || queries == null) {
                            continue;
                        }
                        JSONArray queriesArray = JSONArray.parseArray(queries);
                        String resultsJson = queriesArray.getJSONObject(0).getString("results");
                        if ("".equals(resultsJson) || resultsJson == null) {
                            continue;
                        }
                        JSONArray resultArray = JSONArray.parseArray(resultsJson);
                        String valueJson = resultArray.getJSONObject(0).getString("values");
                        if ("".equals(valueJson) || valueJson == null) {
                            continue;
                        }
                        JSONArray array = JSONArray.parseArray(valueJson);
                        //将数据输出到文本文档中
                        for (int l = 0; l < array.size(); l++) {
                            String time = String.valueOf(array.getJSONArray(l).get(0));
                            String colldata = kpiCode + "\001" + unidId + "\001" + stampToDate(time) + "\001" + stampToDate(time) + "\001" + array.getJSONArray(l).get(1) + "\001" + ext_unitid + "\001" + areaFlag;
                            appendData(file, colldata);

                        }

                    }
                }

            }
            logger.info(areaFlag + "子对象已采集" + sumChild);
        }
        //控制按天写入文件中
        String hdfsPath = null;
        if ("0".equals(timeFlag)) {
            //标志为0，hdfs路径为按天采集路径、
            hdfsPath = "/user/xxjsb_zk/" + fileClass + "/performance/bnms/original/" + year + "/" + date + "/" + filename;
        } else if ("1".equals(timeFlag)) {
            hdfsPath = "/user/xxjsb_zk/" + fileClass + "/now/" + "month/" + filename;
        }
        new HdfsAPP().writeHDFS(file, hdfsPath);


        MyUtil.delFile("/root/datas/", filename);
        System.out.println(filename + "文件已删除！");
    }

    /**
     * 获取四个地区的数据，将数据写入到一个文件中
     *
     * @param ip
     * @param startTime
     * @param endTime
     * @param timeFlag
     */
    @Override
    public void getYesData(String ip, String startTime, String endTime, String timeFlag) {
        //地区标志
        String areaFlag = null;
        if (Constants.IP_BEIJING.equals(ip)) {
            areaFlag = "100";
        } else if (Constants.IP_SHANGHAI.equals(ip)) {
            areaFlag = "101";
        } else if (Constants.IP_NANJING.equals(ip)) {
            areaFlag = "102";
        } else if (Constants.IP_TIANJIN.equals(ip)) {
            areaFlag = "103";
        }
        List<ManageObject> managementList = historyDataDao.getManageDataByAreaflag(areaFlag);
        String date = stampToDate1(startTime);
        String timeDay = date.split(" ")[0].replaceAll("-", "");
        String filename = "hisData" + timeDay + ".txt";

        String file = "/root/datas/" + filename;
        String url = "http://" + ip + ":9200/api/v1/datapoints/query";
        String hosttype = null;
        String domain = null;
        String uuid = null;
        String kpiCode = null;
        String classname = null;
        String ext_unitid = null;
        String unidId = null;
        List<Map> classList;


        //添加计数器记录遍历管理对象数量
        int sum = 0;
        for (ManageObject manageobject : managementList) {
            sum++;
            hosttype = manageobject.getClassName();
            domain = manageobject.getDomain();
            uuid = manageobject.getUuid();
            ext_unitid = hosttype + ":" + domain + ":" + uuid;  //classname:domain:uuid
            //得到管理对象指标列表
            classList = historyDataDao.getkpiListByClassname(hosttype, "1");
            //遍历管理对象
            for (Map map : classList) {
                classname = (String) map.get("KPI_NAME");
                kpiCode = (String) map.get("KPI_CODE");
                //封装请求参数
                JSONObject params = new JSONObject();
                JSONArray jsonArray = new JSONArray();
                JSONObject jsonMo = new JSONObject();
                String[] arr = {hosttype + ".domain=\"" + domain + "\",uuid=\"" + uuid + "\""};
                jsonMo.put("mo", arr);
                JSONObject jsonTags = new JSONObject();
                jsonTags.put("tags", jsonMo);
                jsonTags.put("name", classname);
                jsonArray.add(jsonTags);
                params.put("metrics", jsonArray);
                params.put("start_absolute", startTime);
                params.put("end_absolute", endTime);
                //调用请求接口
                JSONObject jsonObject = null;
                boolean flag = false;
                //连接重置时重试5次
                int times = 0;
                do {
                    try {
                        jsonObject = MyUtil.doPost(url, params);
                    } catch (Exception e) {
                        e.printStackTrace();
                        logger.warn("WARN!" + "取对象= " + ext_unitid + ",指标=" + classname + ",kpicode=" + kpiCode + ",异常，进行重试！");
                        logger.info("请求参数为：==========" + params);
                        try {
                            Thread.sleep(5000);
                        } catch (Exception e1) {
                            e1.printStackTrace();
                        }
                        flag = true;
                        jsonObject = null;
                        logger.info("请求次数==========" + times);
                        times++;
                        if (times > 5) {
                            break;
                        }
                    }

                } while (flag);
                if (jsonObject == null) {
                    continue;
                }
                unidId = ext_unitid + ":" + classname;
                //解析返回的历史数据
                String queries = jsonObject.getString("queries");
                if ("".equals(queries) || queries == null) {
                    continue;
                }
                JSONArray queriesArray = JSONArray.parseArray(queries);
                String resultsJson = queriesArray.getJSONObject(0).getString("results");
                if ("".equals(resultsJson) || resultsJson == null) {
                    continue;
                }
                JSONArray resultArray = JSONArray.parseArray(resultsJson);
                String valueJson = resultArray.getJSONObject(0).getString("values");
                if ("".equals(valueJson) || valueJson == null) {
                    continue;
                }
                JSONArray array = JSONArray.parseArray(valueJson);
                //将数据输出到文本文档中
                for (int i = 0; i < array.size(); i++) {
                    String time = String.valueOf(array.getJSONArray(i).get(0));
                    String colldata = kpiCode + "\001" + unidId + "\001" + stampToDate(time) + "\001" + stampToDate(time) + "\001" + array.getJSONArray(i).get(1) + "\001" + ext_unitid + "\001" + areaFlag;
                    appendData(file, colldata);

                }

            }
            logger.info(areaFlag + "管理对象采集完成数量：" + sum);
        }

        //查询管理对象列表
        List<ManageObject> managementListChild = historyDataDao.getManageDataByAreaflag(areaFlag);
        String childValue = null;
        String childName = null;
        String childId = null;

        //加入子对象数据的采集
        //1.获取子对象列表
        int sumChild = 0;
        for (ManageObject manageObject : managementListChild) {
            sumChild++;
            uuid = manageObject.getUuid();
            hosttype = manageObject.getClassName();
            domain = manageObject.getDomain();
            ext_unitid = hosttype + ":" + domain + ":" + uuid;
            //根据管理对象类型查看子对象和uuid
            List<String> childList = historyDataDao.queryChildInfByClassname(manageObject.getClassName());
            if (childList.size() == 0) {
                continue;
            }
            for (int i = 0; i < childList.size(); i++) {
                childName = childList.get(i);
                String urlChild = "http://" + ip + ":8082/query/mo/" + childName + "?where=uuid='" + uuid + "'";
                JSONArray result = null;
                try {
                    result = doGetArray(urlChild);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                //解析结果
                for (int j = 0; j < result.size(); j++) {

                    JSONObject job = result.getJSONObject(j);
                    String pro = job.getString("properties");
                    JSONArray proArray = JSONArray.parseArray(pro);
                    for (int k = 0; k < proArray.size(); k++) {
                        JSONObject jsonObject = proArray.getJSONObject(k);
                        if ("name".equals(jsonObject.getString("name")))
                            //子对象值
                            childValue = JSONObject.parseObject(jsonObject.getString("value")).getString("value");
                        if ("id".equals(jsonObject.getString("name")))
                            //子对象id
                            childId = JSONObject.parseObject(jsonObject.getString("value")).getString("value");
                    }

                    List<Map> kpiList = historyDataDao.getChildListByClassname(childName, "1");
                    //遍历子对象名称列表
                    for (Map map : kpiList) {
                        classname = (String) map.get("KPI_NAME");
                        kpiCode = (String) map.get("KPI_CODE");
                        //封装请求参数
                        JSONObject params = new JSONObject();
                        JSONArray jsonArray = new JSONArray();
                        JSONObject jsonMo = new JSONObject();
                        String[] arr = {childName + ".id=\"" + childId + "\",name=\"" + childValue + "\",uuid=\"" + uuid + "\""};
                        jsonMo.put("mo", arr);
                        JSONObject jsonTags = new JSONObject();
                        jsonTags.put("tags", jsonMo);
                        jsonTags.put("name", classname);
                        jsonArray.add(jsonTags);
                        params.put("metrics", jsonArray);
                        params.put("start_absolute", startTime);
                        params.put("end_absolute", endTime);

                        //调用请求接口
                        JSONObject jsonObject = null;
                        boolean flag = false;
                        int times = 0;
                        do {
                            try {
                                jsonObject = MyUtil.doPost(url, params);
                            } catch (Exception e) {
                                e.printStackTrace();
                                logger.warn("WARN!" + "取对象= " + ext_unitid + ",指标=" + classname + ",kpicode=" + kpiCode + ",异常，进行重试！");
                                logger.info("请求参数为：==========" + params);
                                try {
                                    Thread.sleep(5000);
                                } catch (Exception e1) {
                                    e1.printStackTrace();
                                }
                                flag = true;
                                jsonObject = null;
                                times++;
                                logger.info("请求次数==========" + times);
                                if (times > 5) {
                                    break;
                                }
                            }

                        } while (flag);
                        if (jsonObject == null) {
                            continue;
                        }
                        unidId = ext_unitid + ":" + childValue + ":" + classname;
                        //解析返回的历史数据
                        String queries = jsonObject.getString("queries");
                        if ("".equals(queries) || queries == null) {
                            continue;
                        }
                        JSONArray queriesArray = JSONArray.parseArray(queries);
                        String resultsJson = queriesArray.getJSONObject(0).getString("results");
                        if ("".equals(resultsJson) || resultsJson == null) {
                            continue;
                        }
                        JSONArray resultArray = JSONArray.parseArray(resultsJson);
                        String valueJson = resultArray.getJSONObject(0).getString("values");
                        if ("".equals(valueJson) || valueJson == null) {
                            continue;
                        }
                        JSONArray array = JSONArray.parseArray(valueJson);
                        //将数据输出到文本文档中
                        for (int l = 0; l < array.size(); l++) {
                            String time = String.valueOf(array.getJSONArray(l).get(0));
                            String colldata = kpiCode + "\001" + unidId + "\001" + stampToDate(time) + "\001" + stampToDate(time) + "\001" + array.getJSONArray(l).get(1) + "\001" + ext_unitid + "\001" + areaFlag;
                            appendData(file, colldata);

                        }

                    }
                }

            }
            logger.info(areaFlag + "子管理对象已采集" + sumChild);
        }
        Date date1 = new Date();
        historyDataDao.insertTbCollDataLogs(RandomGUID.getRandomGUID(), areaFlag + "end", sdf1.format(date1), "end");

    }


    @Override
    @Transactional
    public void getStaticByThread(String ip, String cascade) throws Exception {
        //地区标志
        String areaFlag = null;
        if (Constants.IP_BEIJING.equals(ip)) {
            areaFlag = "100";
        } else if (Constants.IP_SHANGHAI.equals(ip)) {
            areaFlag = "101";
        } else if (Constants.IP_NANJING.equals(ip)) {
            areaFlag = "102";
        } else if (Constants.IP_TIANJIN.equals(ip)) {
            areaFlag = "103";
        }
        // 新启动一个线程
        // 插入一条日志记录接口调用情况（tb_coll_data_logs）
        try {
            Thread.sleep(15000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //查询管理对象列表
        List<ManageObject> managementList = historyDataDao.getManageDataByAreaflag(areaFlag);
        String hosttype = null;
        String domain = null;
        String uuid = null;
        String kpiCode = null;
        String classname = null;
        String ext_unitid = null;
        String dataTime = null;
        String unidId = null;
        String kpiDesc = null;
        String childName = null;
        List<TbCdeInformation> list = new ArrayList<>();
        //遍历管理对象每次取一个管理对象
        for (ManageObject manageObject : managementList) {
            String url = "http://" + ip + ":8082/mo/" + manageObject.getClassName() + ".domain=" + manageObject.getDomain() + ",uuid=" + manageObject.getUuid() + "?cascade=" + cascade;
            JSONObject result = doGet(url);
            //解析结果
            String properties = result.getString("properties");
            JSONArray proArray = JSONArray.parseArray(properties);

            //获取插入时间
            dataTime = sdf.format(new Date());
            hosttype = manageObject.getClassName();
            domain = manageObject.getDomain();
            uuid = manageObject.getUuid();
            ext_unitid = hosttype + ":" + domain + ":" + uuid;
            //查询哪些指标需要存入到静态指标表中
            List<Map> kpiList = historyDataDao.getkpiListByClassname(manageObject.getClassName(), "0");

            for (Map map : kpiList) {
                classname = (String) map.get("KPI_NAME");
                kpiCode = (String) map.get("KPI_CODE");
                kpiDesc = (String) map.get("KPI_DESC");
                unidId = ext_unitid + ":" + classname;
                TbCdeInformation tbCdeInformation = new TbCdeInformation();
                for (int i = 0; i < proArray.size(); i++) {
                    JSONObject job = proArray.getJSONObject(i);
                    if (classname.equals(job.getString("name")))
                        tbCdeInformation.setKpiValue(JSONObject.parseObject(job.getString("value")).getString("value"));

                }
                tbCdeInformation.setInfoId(RandomGUID.getRandomGUID());
                tbCdeInformation.setDateTime(dataTime);
                tbCdeInformation.setExtUnitId(ext_unitid);
                tbCdeInformation.setUnitId(unidId);
                tbCdeInformation.setKpiName(kpiDesc);
                tbCdeInformation.setKpiCode(kpiCode);
                tbCdeInformation.setAreaflag(areaFlag);
                //将静态管理对象加入到list中
                list.add(tbCdeInformation);
//                historyDataDao.insertStaticData(tbCdeInformation);
            }


        }
        save(list);
        //加入子对象数据的采集
        //查询管理对象列表
        List<TbCdeInformation> chiList = new ArrayList<>();

        List<ManageObject> managementListChild = historyDataDao.getManageDataByAreaflag(areaFlag);
        //加入子对象数据的采集
        //1.获取子对象列表
        for (ManageObject manageObject : managementListChild) {
            //根据管理对象类型查看子对象和uuid
            List<String> childList = historyDataDao.queryChildInfByClassname(manageObject.getClassName());
            if (childList.size() == 0) {
                continue;
            }
            //获取插入时间
            dataTime = sdf.format(new Date());
            hosttype = manageObject.getClassName();
            domain = manageObject.getDomain();
            uuid = manageObject.getUuid();
            ext_unitid = hosttype + ":" + domain + ":" + uuid;
            for (int i = 0; i < childList.size(); i++) {
                childName = childList.get(i);
                String url = "http://" + ip + ":8082/query/mo/" + childName + "?where=uuid='" + uuid + "'";
                JSONArray result = doGetArray(url);
                //解析结果
                for (int j = 0; j < result.size(); j++) {
                    JSONObject job = result.getJSONObject(j);
                    String pro = job.getString("properties");
                    JSONArray proArray = JSONArray.parseArray(pro);
                    //获取子对象名称列表
                    List<Map> kpiList = historyDataDao.getChildListByClassname(childName, "0");

                    if (kpiList.size() == 0 || kpiList == null) {
                        continue;
                    }
                    //遍历子对象名称，获取子对象静态指标数据
                    for (Map map : kpiList) {
                        classname = (String) map.get("KPI_NAME");
                        kpiCode = (String) map.get("KPI_CODE");
                        kpiDesc = (String) map.get("KPI_DESC");
                        unidId = ext_unitid + ":" + childName + ":" + classname;
                        TbCdeInformation tbCdeInformation = new TbCdeInformation();
                        for (int m = 0; m < proArray.size(); m++) {
                            JSONObject job1 = proArray.getJSONObject(m);
                            if (classname.equals(job1.getString("name")))
                                tbCdeInformation.setKpiValue(JSONObject.parseObject(job1.getString("value")).getString("value"));
                        }
                        tbCdeInformation.setInfoId(RandomGUID.getRandomGUID());
                        tbCdeInformation.setDateTime(dataTime);
                        tbCdeInformation.setExtUnitId(ext_unitid);
                        tbCdeInformation.setUnitId(unidId);
                        tbCdeInformation.setKpiName(kpiDesc);
                        tbCdeInformation.setKpiCode(kpiCode);
                        tbCdeInformation.setAreaflag(areaFlag);
                        chiList.add(tbCdeInformation);
                    }

                }

            }
        }
        save(chiList);
    }

    /**
     * 批量插入静态数据
     *
     * @param tbCdeInformationList
     * @throws Exception
     */
    public void save(List<TbCdeInformation> tbCdeInformationList) throws Exception {

        int batchCount = 1000;//每批commit的个数
        int batchLastIndex = batchCount - 1;//每批最后一个的下标
        for (int index = 0; index < tbCdeInformationList.size() - 1; ) {
            if (batchLastIndex > tbCdeInformationList.size() - 1) {
                batchLastIndex = tbCdeInformationList.size() - 1;
                historyDataDao.insertStaticData(tbCdeInformationList.subList(index, batchLastIndex));
                System.out.println("index:" + index + "     batchLastIndex:" + batchLastIndex);
                break;//数据插入完毕,退出循环

            } else {
                historyDataDao.insertStaticData(tbCdeInformationList.subList(index, batchLastIndex));
                System.out.println("index:" + index + "     batchLastIndex:" + batchLastIndex);
                index = batchLastIndex + 1;//设置下一批下标
                batchLastIndex = index + (batchCount - 1);
            }
        }

    }

    @Override
    public boolean isOrNotEnd() {
        Date today = new Date();
        String date = sdf1.format(today);
        List<String> endTitle = historyDataDao.getTitle(date);

        if (endTitle.contains("100end") && endTitle.contains("102end") && endTitle.contains("103end")) {
            return true;
        }
        return false;
    }
}
